<template>
  <div class="trademark">
    <el-card>
      <el-button type="primary" icon="Plus" @click="addTrademark"
        >添加品牌</el-button
      >
      <!-- 表格组件 -->
      <el-table border :data="trademarkArr">
        <el-table-column
          label="序号"
          align="center"
          width="80px"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <el-image :src="row.logoUrl" style="width: 100px; height: 100px" />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #="{ row, $index }">
            <el-button
              icon="Edit"
              type="primary"
              size="small"
              @click="updateTrademark(row)"
            ></el-button>
            <!-- 气泡框组件 -->
            <el-popconfirm
              :title="`你确定要删除${row.tmName}吗`"
              width="260"
              @confirm="removeTrademark(row.id)"
            >
              <template #reference>
                <el-button
                  icon="Delete"
                  type="primary"
                  size="small"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 6, 9, 11]"
        background
        layout="prev, pager, next, jumper,->, sizes,total"
        :total="total"
        @change="getHasTrademark"
      />
    </el-card>
    <!-- 对话框组件 -->
    <el-dialog
      v-model="dialogVisible"
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
    >
      <el-form
        label-width="100px"
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            placeholder="请输入品牌名称"
            v-model="trademarkParams.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 上传组件 -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 具名插槽 footer -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handlerCancel">取消</el-button>
          <el-button type="primary" @click="handlerConfirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineOptions, ref, onMounted, watch, reactive } from "vue";
import {
  reqHasTrademark,
  reqAddOrUpdate,
  reqDeleteTrademark,
} from "@/api/product/trademark";
import type { TradeMark } from "@/api/product/trademark/type";
import { ElMessage, type UploadProps } from "element-plus";
defineOptions({
  name: "Trademark",
});
onMounted(() => {
  getHasTrademark();
});
let currentPage = ref(1); //当前页码
let pageSize = ref(3); //当前数据条数
let total = ref(0); //总的数据条数
let trademarkArr = ref<TradeMark[]>([]); //储存已有品牌的数据初始化
let dialogVisible = ref(false); //对话框
let formRef = ref(); //获取表单el-form元素
//收集品牌属性
let trademarkParams = reactive<TradeMark>({
  tmName: "",
  logoUrl: "",
});
//获取已有品牌的回调函数
const getHasTrademark = async () => {
  let result = await reqHasTrademark(currentPage.value, pageSize.value);
  // console.log(result);
  if (result.code == 200) {
    total.value = result.data.total;
    trademarkArr.value = result.data.records;
  }
};
//监听数据条数的变化
watch([pageSize], () => {
  currentPage.value = 1;
});
//添加按钮的回调
const addTrademark = () => {
  dialogVisible.value = true;
  Object.assign(trademarkParams, {
    id: "",
    tmName: "",
    logoUrl: "",
  });
  //清除表单验证以及表单内容
  formRef.value?.resetFields();
};
//更新按钮的回调
const updateTrademark = (row: TradeMark) => {
  Object.assign(trademarkParams, row);
  dialogVisible.value = true;
  //清空清理某个字段的表单验证信息
  formRef.value?.clearValidate("tmName");
  formRef.value?.clearValidate("logoUrl");
};
//上传图片之前触发的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // console.log(rawFile);
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      //清除某个字段的校验
      formRef.value.clearValidate("logoUrl");
      return true;
    } else {
      ElMessage({
        type: "error",
        message: "图片大小超过4M",
      });
      return false;
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传图片格式必须为image/png|image/jpeg|image/gif",
    });
    return false;
  }
};
//图片上传成功之后触发的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // console.log(response);
  trademarkParams.logoUrl = response.data;
};
//自定义校验规则
const validatorTmName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback();
  } else {
    callback(new Error("输入的内容必须大于2位数"));
  }
};
const validatorLogoUrl = (rule: any, value: any, callback: any) => {
  if (value) {
    callback();
  } else {
    callback(new Error("图片不能为空"));
  }
};
//表单校验规则
const rules = reactive({
  tmName: [{ required: true, trigger: "blur", validator: validatorTmName }],
  logoUrl: [{ required: true, validator: validatorLogoUrl }],
});
//对话框取消按钮的回调
const handlerCancel = () => {
  dialogVisible.value = false;
};
//对话框确定按钮的回调
const handlerConfirm = async () => {
  await formRef.value.validate();

  let result = await reqAddOrUpdate(trademarkParams);
  // console.log(result);
  if (result.code == 200) {
    //关闭对话框
    dialogVisible.value = false;
    ElMessage({
      type: "success",
      message: trademarkParams.id ? "品牌数据修改成功" : "品牌数据添加成功",
    });
    //判断trademarkParams.id是否为假;为假时为添加;添加时页码回到首页
    if (!trademarkParams.id) {
      currentPage.value = 1;
    }
    //重新获取数据
    getHasTrademark();
  } else {
    ElMessage({
      type: "error",
      message: trademarkParams.id ? "品牌数据修改失败" : "品牌数据添加失败",
    });
    //关闭对话框
    dialogVisible.value = false;
  }
};
//删除某个已有品牌数据的回调函数
const removeTrademark = async (id: number) => {
  let result = await reqDeleteTrademark(id);
  if (result.code == 200) {
    ElMessage({
      type: "success",
      message: "删除成功",
    });
    getHasTrademark();
  } else {
    ElMessage({
      type: "error",
      message: "删除失败",
    });
  }
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped lang="scss">
.trademark {
  .el-table {
    margin-top: 20px;
  }
  .el-pagination {
    margin-top: 20px;
  }
}
</style>
